package leetcode.listnode;

public class AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode node1 = l1;
        ListNode node2 = l2;

        int addNum = 0;
        addNum = node1.val + node2.val + addNum;
        ListNode node = new ListNode(addNum % 10);
        addNum = addNum / 10;
        ListNode head = node;

        while (true) {
            node1 = node1 == null ? null : node1.next;
            node2 = node2 == null ? null : node2.next;

            if (node1 == null && node2 != null) {
                addNum = addNum + node2.val;
            } else if (node2 == null && node1 != null) {
                addNum = addNum + node1.val;
            } else if (node2 != null && node1 != null) {
                addNum = addNum + node1.val + node2.val;
            } else if (node2 == null && node1 == null) {
                break;
            }

            head.next = new ListNode(addNum % 10);
            addNum = addNum / 10;
            head = head.next;

        }

        if (addNum == 1){
            head.next = new ListNode(1);
        }

        return node;
    }

}
